package com.youlai.system.controller.asset;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youlai.system.common.result.PageResult;
import com.youlai.system.common.result.Result;
import com.youlai.system.common.util.ExcelUtils;
import com.youlai.system.model.entity.AssetComputer;
import com.youlai.system.model.entity.SysUser;
import com.youlai.system.model.form.ComputerForm;
import com.youlai.system.model.form.DeptForm;
import com.youlai.system.model.form.UserForm;
import com.youlai.system.model.query.ComputerPageQuery;
import com.youlai.system.model.query.UserPageQuery;
import com.youlai.system.model.vo.*;
import com.youlai.system.plugin.dupsubmit.annotation.PreventDuplicateSubmit;
import com.youlai.system.plugin.easyexcel.ComputerImportLisenter;
import com.youlai.system.plugin.easyexcel.UserImportListener;
import com.youlai.system.service.AssetComputerService;
import com.youlai.system.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author bill
 */
@RestController
@RequestMapping("/api/v1/asset/computer")
@RequiredArgsConstructor
public class ComputerController {

    private final AssetComputerService assetComputerService;
    private final SysUserService sysUserService;

    @Operation(summary = "计算机分页列表")
    @GetMapping("/page")
    public PageResult<AssetComputerPageVO> listPagedComputers(
            @ParameterObject ComputerPageQuery queryParams
    ) {
        return PageResult.success(assetComputerService.listPagedComputers(queryParams));
    }

    @Operation(summary = "添加计算机设备")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('asset:computer:add')")
    public Result saveComputer(@Valid @RequestBody ComputerForm computerForm) {
        Long computerId = assetComputerService.saveComputer(computerForm);
        return Result.success(computerId);
    }

    @Operation(summary = "电脑表单数据")
    @GetMapping("/{computerId}/form")
    public Result<ComputerForm> getComputerForm(
            @Parameter(description = "设备id") @PathVariable Long computerId
    ) {
        ComputerForm formData = assetComputerService.getComputerFormData(computerId);
        return Result.success(formData);
    }

    @Operation(summary = "修改用户")
    @PutMapping(value = "/{computerId}")
    @PreAuthorize("@ss.hasPerm('asset:computer:edit')")
    public Result updateComputer(
            @Parameter(description = "设备ID") @PathVariable Long computerId,
            @RequestBody @Validated ComputerForm computerForm) {
        boolean result = assetComputerService.updateComputer(computerId, computerForm);
        return Result.judge(result);
    }

    @Operation(summary = "删除电脑")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('asset:computer:delete')")
    public Result deleteComputer(
            @Parameter(description = "电脑ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = assetComputerService.deleteComputer(ids);
        return Result.judge(result);
    }

    @Operation(summary = "用户导入模板下载")
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        String fileName = "电脑导入模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        String fileClassPath = "excel-templates" + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);

        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();

        excelWriter.finish();
    }

    @Operation(summary = "导入电脑")
    @PostMapping("/import")
    public Result importComputers(MultipartFile file) throws IOException {
        ComputerImportLisenter computerImportListener = new ComputerImportLisenter(sysUserService.list(), assetComputerService.list(), assetComputerService);
        String msg = ExcelUtils.importExcel(file.getInputStream(), AssetComputerImportVO.class, computerImportListener);
        return Result.success(msg);
    }

    @Operation(summary = "导出电脑")
    @GetMapping("/export")
    public void exportComputers(ComputerPageQuery queryParams, HttpServletResponse response) throws IOException {
        String fileName = "电脑资产.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        List<AssetComputerImportVO> exportUserList = assetComputerService.listExportComputers(queryParams);
        EasyExcel.write(response.getOutputStream(), UserExportVO.class).sheet("电脑资产")
                .doWrite(exportUserList);
    }
}
